package io.renren.modules.tag.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.lables.entity.UserTag;
import io.renren.modules.lables.service.UserTagService;
import io.renren.modules.tag.dto.TagsBasicInfoDto;
import io.renren.modules.tag.entity.*;
import io.renren.modules.tag.service.TagRulesService;
import io.renren.modules.tag.service.TagsBasicInfoService;
import io.renren.modules.tag.utils.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static io.renren.modules.tag.utils.SqlUtils.getUsers;

@RestController
@Slf4j
public class DataFormController {
@Autowired
private TagRulesService tagRulesService;
@Autowired
private TagsBasicInfoService tagsBasicInfoService;
@Autowired
private SnowFlake snowFlake;
@Autowired
private UserTagService userTagService;
    @PostMapping("/process-data")
    public R processData(@RequestBody TagRulesData tagRulesData) {
        // 在这里处理传入的数据
        log.debug("Received data: " + tagRulesData);
        TagsBasicInfoEntity entity = new TagsBasicInfoEntity();
        TagsBasicInfoDto tagsBasicInfo = tagRulesData.getTagsBasicInfo();
        BeanUtils.copyProperties(tagsBasicInfo,entity);
        tagsBasicInfoService.save(entity);
        Integer id = entity.getId();
        Integer tagCreateWay = tagRulesData.getTagCreateWay();
        List<Layering> layeringList = tagRulesData.getLayeringList();
        for (Layering layering : layeringList) {
            String levelName = layering.getLevelName();
            String levelDescription = layering.getLevelDescription();
            String groupOp = layering.getOp();
            List<AttributesRules> rules = layering.getAttributesRules();
            List<Map<String, Object>> users = new ArrayList<>();
            for (AttributesRules action : rules) {
                List<Map<String, Object>> extracted = extracted(tagCreateWay, levelName, levelDescription, action, groupOp, id);
                if (action.getOp().equals("and")) {
                    if (users.isEmpty()) {
                        users.addAll(extracted);
                    } else {
                        users.retainAll(extracted); // Intersection
                    }
                } else {
                    users.addAll(extracted); // Union
                }
            }
            List<AttributesRules> behaviorRules = layering.getBehaviorRules();
            List<Map<String, Object>> behaviorUsers = new ArrayList<>();
            for (AttributesRules behavior : behaviorRules) {
                List<Map<String, Object>> extracted = extracted(tagCreateWay, levelName, levelDescription, behavior, groupOp, id);
                if (behavior.getOp().toLowerCase().equals("and")) {
                    if (behaviorUsers.isEmpty()) {
                        behaviorUsers.addAll(extracted);
                    } else {
                        behaviorUsers.retainAll(extracted); // Intersection
                    }
                } else {
                    behaviorUsers.addAll(extracted); // Union
                }
            }
            if (groupOp.toLowerCase().equals("and")) {
                users.addAll(behaviorUsers);
            } else {
                users.addAll(behaviorUsers);
            }
            for (Map<String, Object> user : users) {
                UserTag userTag = new UserTag();
                userTag.setTagName((String) user.get("property_name"));
                userTag.setTagValue(levelName);
                userTag.setUserId((Long) user.get("id"));
                userTag.setDistinctId((snowFlake.nextId()));
                userTag.setInsertTime(LocalDateTime.now());
                userTag.setSubject(levelName);
                userTagService.save(userTag);
            }
        }
        return R.ok();
    }

    private List<Map<String, Object>> extracted(Integer tagCreateWay, String levelName, String levelDescription, AttributesRules action, String groupOp, Integer id) {
        String relation = action.getRelation();
        Integer mode = action.getMode();
        TagRulesEntity entity = new TagRulesEntity();
        entity.setTagInfoId(id);
        entity.setTagCreateWay(tagCreateWay);
        entity.setOp(action.getOp());
        entity.setRelation(relation);
        entity.setLevelName(levelName);
        entity.setPropertyName(action.getPropertyName());
        entity.setValue(action.getValue());
        entity.setValueType(action.getValueType());
        entity.setPropertyId(action.getPropertyId());
        entity.setLevelDescription(levelDescription);
        entity.setRelation(relation);
        entity.setTagCreateMode(mode);
        entity.setGroupOp(groupOp);
        tagRulesService.save(entity);
        return getUsers(entity);
    }

    @GetMapping("/tag")
    public String getTag(@RequestParam Map<String, Object> params) {
        PageUtils page = tagRulesService.queryPage(params);
        List<?> list = page.getList();

        JSONObject json = new JSONObject();
        json.put("tagCreateWay", 4);
        json.put("tagCreateName", "自定义");

        JSONObject tagsBasicInfo = new JSONObject();
        tagsBasicInfo.put("subjectId", 123456);
        tagsBasicInfo.put("subjectName", "重大行政处罚案件所涉人员");
        tagsBasicInfo.put("displayName", "涉赌");
        tagsBasicInfo.put("tagName", "涉赌");
        tagsBasicInfo.put("tagGroup", "业务域");
        tagsBasicInfo.put("tagGroupId", 14);
        tagsBasicInfo.put("notes", "自定义标签");
        json.put("tagsBasicInfo", tagsBasicInfo);

        JSONArray layeringList = new JSONArray();
        JSONObject layering = new JSONObject();
        layering.put("levelName", "分层1");
        layering.put("levelDescription", "123123");
        layering.put("op", "and");

        JSONArray attributesRules = new JSONArray();
        JSONObject attributesRule1 = new JSONObject();
        attributesRule1.put("op", "or");
        attributesRule1.put("propertyName", "特特");
        attributesRule1.put("propertyId", 4);
        attributesRule1.put("valueType", "字符串");
        attributesRule1.put("relation", "ne");
        attributesRule1.put("value", "123");
        attributesRule1.put("mode", 1);
        attributesRules.add(attributesRule1);

        JSONObject attributesRule2 = new JSONObject();
        attributesRule2.put("op", "or");
        attributesRule2.put("propertyName", "特特");
        attributesRule2.put("propertyId", 3);
        attributesRule2.put("valueType", "字符串");
        attributesRule2.put("relation", "le");
        attributesRule2.put("value", "123");
        attributesRule2.put("mode", 1);
        attributesRules.add(attributesRule2);

        layering.put("attributesRules", attributesRules);

        JSONArray behaviorRules = new JSONArray();
        JSONObject behaviorRule1 = new JSONObject();
        behaviorRule1.put("op", "and");
        behaviorRule1.put("relation", "notdo");
        behaviorRule1.put("propertyName", "qweq");
        behaviorRule1.put("propertyId", 2);
        behaviorRule1.put("valueType", "字符串");
        behaviorRule1.put("value", "123");
        behaviorRule1.put("mode", 2);
        behaviorRules.add(behaviorRule1);

        JSONObject behaviorRule2 = new JSONObject();
        behaviorRule2.put("op", "or");
        behaviorRule2.put("relation", "");
        behaviorRule2.put("propertyName", "");
        behaviorRule2.put("propertyId", 1);
        behaviorRule2.put("valueType", "字符串");
        behaviorRule2.put("value", "");
        behaviorRule2.put("mode", 2);
        behaviorRules.add(behaviorRule2);

        layering.put("behaviorRules", behaviorRules);

        layeringList.add(layering);
        json.put("layeringList", layeringList);

        return json.toJSONString();
    }
}
